package com.lifeng.controller;

import com.lifeng.bean.User;
import com.lifeng.config.MyTestConfig;
import com.lifeng.config.MyTestConfig2;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by lifeng on 2018/4/13.
 * 服务提供方
 */
@RestController
public class UserProviderCotroller {
    private static final Logger log = LoggerFactory.getLogger(UserProviderCotroller.class);

    @Autowired
    private EurekaClient eurekaClient;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private MyTestConfig myTestConfig;
    @Autowired
    private MyTestConfig2 myTestConfig2;
    @Value("${test.my.name}")
    private String myname;

    /**@GetMapping 相当于 get请求 */
    @GetMapping("/user/{id}")
    public Object findById(@PathVariable String id){
        User user = new User();
        user.setId(id);
        user.setName("张洒");
        user.setBirthday(new Date());
        log.info("新的请求到达");
        log.info("====>"+myTestConfig.userName);
        log.info("====>"+myTestConfig2.name);
        log.info("====>"+myname);
        return user;
    }

    @RequestMapping("/user")
    public Object add(User user, HttpServletRequest request){
        log.info("user save..."+request.getParameter("name"));
        log.info("name:"+user.getName());
        return user;
    }

    /** 通过服务提供者名称从服务发现中心获取服务url*/
    @GetMapping("/getServiceUrl")
    public String getServiceUrl(){
        //第二个参数是否安全认证
        InstanceInfo instanceInfo = eurekaClient.getNextServerFromEureka("user-service-provider",false);
        return instanceInfo.getHomePageUrl();
    }

    /**获取当前服务的详细信息*/
    @GetMapping("/getServiceInfo")
    public ServiceInstance getServiceInfo(){
        System.out.println(discoveryClient.getServices());//获取所有的服务
        System.out.println(discoveryClient.getInstances("user-service-provider").get(0).getUri().toString());
        return discoveryClient.getInstances("user-service-provider").get(0);
    }
}
